package com.frank.subject.domain.util;

import com.alibaba.fastjson2.JSON;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * @author Frank Zou
 * @version v0.0.1
 * @date 2024/4/9
 * @description
 */
@Component
public class CacheUtil<V> {
    private final Cache<String, String> localCache = CacheBuilder.newBuilder()
            .maximumSize(5000)
            .expireAfterWrite(10, TimeUnit.SECONDS)
            .build();

    public List<V> getResult(String cacheKey, Class<V> clazz, Function<String, List<V>> function){
        List<V> result;
        String content = localCache.getIfPresent(cacheKey);
        if (StringUtils.isNotBlank(content)) {
            result = JSON.parseArray(content, clazz);
        }else{
            result = function.apply(cacheKey);
            if (!CollectionUtils.isEmpty(result)){
                localCache.put(cacheKey, JSON.toJSONString(result));
            }
        }
        return result;
    }
}
